<template>
    <el-row>
        <el-col :span="2">
        </el-col>
        <el-col :span="4">
        </el-col>
        <el-col :span="12">
            <el-card class="box-card" style="width: 98%">
                <el-row style="margin-top: 10px;">
                    <el-col :span="1">
                    </el-col>
                    <el-col :span="4">
                        <div class="demo-basic--circle">
                            <div class="block">
                                <el-avatar :size="100"
                                           :src="userInfo.headImg"/>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="18">
                        <el-row style="margin-top: 10px;">
                            <el-col :span="20">
                                <span style="font-size: 30px;font-weight:bold;font-family: 黑体">
                                       {{userInfo.nickname}}
                                    </span>
                            </el-col>
                            <el-col :span="4">
                                <el-button type="success" plain @click="editUserDialogVisible = true">编辑个人信息</el-button>
                            </el-col>


                        </el-row>
                        <el-row style="margin-top: 10px;">
                            <el-col :span="1">
                                <el-icon style="padding-top: 4px" color="#67c23a">
                                    <user/>
                                </el-icon>&nbsp;&nbsp;&nbsp;
                            </el-col>
                            <el-col :span="23">
                                <span style="color: #545c64">
                                       {{userInfo.profession}}
                                    </span>
                            </el-col>

                        </el-row>
                        <el-row style="margin-top: 10px;">
                            <el-col :span="1">
                                <el-icon style="padding-top: 4px" color="#67c23a">
                                    <postcard/>
                                </el-icon>&nbsp;&nbsp;&nbsp;
                            </el-col>
                            <el-col :span="23">
                            <span style="color: #545c64">
                                         {{userInfo.description}}
                                    </span>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="1">
                    </el-col>
                </el-row>
                <el-divider/>
            </el-card>

            <el-card class="box-card" style="width: 98%">
                <el-button-group style="margin-left: 10px">
                    <el-button type="success" @click="selectCondition('asked')">由我提出
                    </el-button>
                    <el-button type="success" @click="selectCondition('answered')">由我回复
                    </el-button>
                </el-button-group>

                <el-scrollbar>
                    <ul v-infinite-scroll="loadBugPageList"
                        class="infinite-list" style="width: 100%">

                        <li v-if="bugList.length === 0">
                            <el-empty description="No Data"/>
                        </li>
                        <li v-else v-for="bug in bugList" :key="bug" class="infinite-list-item pointer"
                            @click="bugDetail(bug)">
                            <el-card style="width: 100%;">

                                <el-row>
                                    <el-col :span="24"><h3> &nbsp;{{bug.title}}</h3></el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">{{bug.description}}</el-col>
                                </el-row>

                                <el-row justify="end" style="width: 100%">

                                    <el-col :span="4" style="margin-top: 10px;">
                                        <el-space wrap>
                                            &nbsp;
                                            <el-icon style="margin-top: 4px;color: #67c23a">
                                                <View/>
                                            </el-icon>
                                            <span style="margin-top: 4px;color: #67c23a">{{bug.views}}</span>
                                        </el-space>
                                        &nbsp;&nbsp;
                                        <el-space wrap>
                                            <el-icon style="margin-top: 4px;color: #67c23a">
                                                <chat-round/>
                                            </el-icon>
                                            <span style="margin-top: 4px;color: #67c23a">{{bug.answers}}</span>
                                        </el-space>
                                    </el-col>
                                    <el-col :span="8" style="margin-top: 10px;">
                                        <el-space wrap>
                                            <el-tag
                                                    v-for="item in bug.categoriesName"
                                                    :key="item"
                                                    type="warning"
                                                    effect="plain"
                                            > {{ item }}
                                            </el-tag>
                                        </el-space>
                                    </el-col>
                                    <el-col :span="12" style="margin-top: 10px;">
                                        <span style="color: #67c23a">{{"「"+bug.nickname +"」于 "+ bug.createTimeStr + " 提出该问题"}} </span>
                                    </el-col>

                                </el-row>

                            </el-card>
                        </li>
                        <el-divider v-if="disabledScroll">没有更多了</el-divider>
                    </ul>
                </el-scrollbar>
            </el-card>

        </el-col>
        <el-col :span="4">
            <el-card class="box-card">
                <template #header>
                    <div class="card-header">
                        <span>个人成就</span>
                    </div>
                </template>
                <el-row style="margin-bottom: 20px;">
                    <el-col >
                        <el-icon color="#67c23a">
                            <chat-round/>
                        </el-icon>
                        提出bug数：{{achievement.askedNum}}
                    </el-col>
                </el-row>

                <el-row style="margin-bottom: 20px;">
                    <el-col>
                        <el-icon color="#67c23a">
                            <chat-line-round/>
                        </el-icon>
                        回答bug数：{{achievement.answeredNum}}
                    </el-col>
                </el-row>
                <el-row style="margin-bottom: 20px;">
                    <el-col>
                        <el-icon color="#67c23a">
                            <circle-check/>
                        </el-icon>
                        被采纳数：{{achievement.acceptNum}}
                    </el-col>
                </el-row>
                <el-row style="margin-bottom: 20px;">
                    <el-col>
                        <el-icon color="#67c23a">
                            <circle-check/>
                        </el-icon>
                        被嫌弃数：{{achievement.rejectNum}}
                    </el-col>
                </el-row>
            </el-card>
        </el-col>
        <el-col :span="2">
        </el-col>
    </el-row>

    <el-drawer
            v-model="detailDialogVisible"
            size="80%"
            :with-header="false"
            :destroy-on-close="true"
    >

        <el-row>
            <el-col :span="24">
                <div class="grid-content bg-purple-dark"></div>
            </el-col>
        </el-row>
        <p style="font-size: 30px;text-align: left;text-indent: 30px">{{detailTitle}}</p>

        <el-timeline>
            <el-timeline-item v-for="(activity, index) in detailList"
                              :key="index"
                              :timestamp="activity.userAction" placement="top">
                <el-card>
                    <md-editor
                            v-model="activity.content"
                            previewOnly
                    />


                    <div style="text-align: right;margin-right: 20px">
                        <el-row>
                            <el-col :span="19"></el-col>
                            <el-col :span="2" v-if="activity.acceptNum != null">

                                <el-row>
                                    <el-col :span="12">
                                        <el-tooltip
                                                class="box-item"
                                                effect="dark"
                                                content="采纳"
                                                placement="bottom"
                                        >
                                            <el-button v-if="activity.currentHasAccept" type="success" circle  @click="acceptAnswer(activity)" :disabled="codeDisabled">
                                                <el-icon>
                                                    <check/>
                                                </el-icon>
                                            </el-button>
                                            <el-button v-else type="success" circle  @click="acceptAnswer(activity)" :disabled="codeDisabled" plain>
                                                <el-icon>
                                                    <check/>
                                                </el-icon>
                                            </el-button>

                                        </el-tooltip>
                                    </el-col>
                                    <el-col :span="12" style="text-align: left">
                                        <span style="font-size:25px;margin-top: 4px;color: #67c23a">{{ activity.acceptNum }}</span>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <el-col :span="2" v-else>
                            </el-col>
                            <el-col :span="2" v-if="activity.rejectNum != null">
                                <el-row>
                                    <el-col :span="12">
                                        <el-tooltip
                                                class="box-item"
                                                effect="dark"
                                                content="无用"
                                                placement="bottom"
                                        >
                                            <el-button v-if="activity.currentHasReject" type="warning" circle  @click="rejectAnswer(activity)" :disabled="codeDisabled">
                                                <el-icon>
                                                    <close/>
                                                </el-icon>
                                            </el-button>
                                            <el-button v-else type="warning" circle  @click="rejectAnswer(activity)" :disabled="codeDisabled" plain>
                                                <el-icon>
                                                    <close/>
                                                </el-icon>
                                            </el-button>
                                        </el-tooltip>
                                    </el-col>
                                    <el-col :span="12" style="text-align: left">
                                        <span style="font-size:25px;margin-top: 4px;color: #E6A23C">{{ activity.rejectNum }}</span>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <el-col :span="2" v-else>
                            </el-col>
                            <el-col :span="1">
                                <el-tooltip
                                        class="box-item"
                                        effect="dark"
                                        content="回复"
                                        placement="bottom"
                                >
                                    <el-icon @click="answerQuestion(activity)" class="pointer" :size="30"
                                             color="#409EFF">
                                        <chat-dot-square/>
                                    </el-icon>
                                </el-tooltip>
                            </el-col>
                        </el-row>
                    </div>
                </el-card>
            </el-timeline-item>

            <el-card v-show="answerQuestionDialogVisible">
                <template #header>
                    <div class="card-header" style="flex-direction: inherit;font-size: 20px">
                        <span>回复「{{ beAnsweredNickname }}」：</span>
                        <el-button type="primary" @click="commitAnswer">提交</el-button>
                    </div>
                </template>
                <md-editor id="answer_question"
                           v-model="answerText"
                           @onUploadImg="onUploadImg"
                           :toolbarsExclude="['save']"
                />
            </el-card>
        </el-timeline>

    </el-drawer>

    <el-dialog v-model="editUserDialogVisible" title="个人信息" width="30%" center>
        <el-form ref="userInfo"
                 label-width="100px"
                 :model="userInfo"
                 style="max-width: 460px"
                 :rules="rules"
        >
            <el-form-item label="昵称">
                <el-input v-model="userInfo.nickname" placeholder="请输入昵称"/>
            </el-form-item>
            <el-form-item label="专业">
                <el-input v-model="userInfo.profession" placeholder="请输入专业"/>
            </el-form-item>
            <el-form-item label="简介">
                <el-input type="textarea"
                          maxlength="200"
                          show-word-limit
                          placeholder="请输入简介"
                          v-model="userInfo.description"/>
            </el-form-item>
            <el-form-item label="头像">
                <el-upload
                        class="avatar-uploader"
                        :action="uploadUrl"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        :headers="headerParams"
                        name="multipartFile"
                >
                    <el-avatar v-if="userInfo.headImg" shape="circle" :size="100" :fit="fit" :src="userInfo.headImg"/>
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus/>
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>

        <template #footer>
      <span class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUserInfo('userInfo')">保存</el-button>
      </span>
        </template>
    </el-dialog>
</template>

<script>
    import {getUserAchievement, pageList, userCenterPageList} from "../../api/bugRecord";
    import {getMurmur, getToken, getUsername} from "../../utils/auth";
    import {list, saveAnswer, updateAcceptReject} from "../../api/bugAnswered";
    import MdEditor from 'md-editor-v3';
    import 'md-editor-v3/lib/style.css';
    import {ElMessage, ElNotification} from 'element-plus'
    import {uploadImp} from "../../api/file";
    import {getUserByUsername, updateByUsername} from "../../api/user";

    export default {
        components: {MdEditor},
        data() {
            return {
                beAnsweredNickname: null,
                achievement: {
                    askedNum: 0,
                    answeredNum: 0,
                    acceptNum: 0,
                    rejectNum: 0
                },
                uploadUrl: '/bsolver-server/file/upload',
                headerParams: {
                    AUTHORIZATION: '',
                    _username: ''
                },
                userInfo: {
                    username: '',
                    nickname: '',
                    profession: '',
                    description: '',
                    headImg: ''
                },
                // 表单验证，需要在 el-form-item 元素中增加 prop 属性
                rules: {
                    nickname: [
                        {required: true, message: '昵称不可为空', trigger: 'blur'}
                    ],
                    profession: [
                        {required: true, message: '专业不可为空', trigger: 'blur'}
                    ],
                    description: [
                        {required: true, message: '请简单的介绍下自己吧', trigger: 'blur'}
                    ],
                    headImg: [
                        {required: true, message: '请上传您的头像', trigger: 'blur'}
                    ],
                },
                editUserDialogVisible: false,
                answerText: '',
                answerQuestionDialogVisible: false,
                beAnsweredUsername: null,
                beAnsweredNickname: null,
                nickname: null,
                registerDialogVisible: false,
                answerQuestionDialogVisible: false,
                detailList: [],
                detailDialogVisible: false,
                detailId: null,
                detailTitle: null,
                disabledScroll: false,
                pageListCondition: {
                    category: null,
                    searchCondition: 'asked',
                    limit: 5,
                    page: 0,
                    username: null

                },
                bugList: [],
                total: 0,
                codeDisabled: false,
            }

        },
        mounted() {
            this.pageListCondition.username = getUsername();
            //this.bugPageList()
            this.getUserInfo();
            this.getUserAchievement();
        },
        methods: {
            rejectAnswer(answer) {
                this.codeDisabled = true;
                if (!getUsername() || !getToken()) {
                    this.codeDisabled = false;
                    this.toHome();
                } else {
                    answer.bugId = this.detailId;
                    answer.flag = 'reject';
                    answer.username = getUsername();
                    updateAcceptReject(answer).then((res) => {
                        if (res.code === 0) {
                            for (let i = 0; i < this.detailList.length; i++) {
                                if (this.detailList[i].id === answer.id) {
                                    if (this.detailList[i].currentHasReject){
                                        this.detailList[i].currentHasReject = false;
                                        this.detailList[i].rejectNum -=1;
                                    }else {
                                        this.detailList[i].currentHasReject = true;
                                        this.detailList[i].rejectNum +=1;
                                        if (this.detailList[i].currentHasAccept){
                                            this.detailList[i].currentHasAccept = false;
                                            this.detailList[i].acceptNum -=1;
                                        }
                                    }
                                    this.codeDisabled = false;
                                    return;
                                }
                            }
                        }
                    })
                }
            },
            acceptAnswer(answer) {
                this.codeDisabled = true;
                if (!getUsername() || !getToken()) {
                    this.codeDisabled = false;
                    this.toHome();
                } else {
                    answer.bugId = this.detailId;
                    answer.flag = 'accept';
                    answer.username = getUsername();
                    updateAcceptReject(answer).then((res) => {
                        if (res.code === 0) {
                            for (let i = 0; i < this.detailList.length; i++) {
                                if (this.detailList[i].id === answer.id) {
                                    if (this.detailList[i].currentHasAccept){
                                        this.detailList[i].currentHasAccept = false;
                                        this.detailList[i].acceptNum -=1;
                                    }else {
                                        this.detailList[i].currentHasAccept = true;
                                        this.detailList[i].acceptNum +=1;
                                        if (this.detailList[i].currentHasReject){
                                            this.detailList[i].currentHasReject = false;
                                            this.detailList[i].rejectNum -=1;
                                        }
                                    }
                                    this.codeDisabled = false;
                                    return;
                                }
                            }
                        }
                    })
                }
            },
            getUserAchievement() {
                getUserAchievement({username: getUsername()}).then((res) => {
                    if (res.code === 0) {
                        this.achievement.askedNum = res.data.askedNum;
                        this.achievement.answeredNum = res.data.answeredNum;
                        this.achievement.rejectNum = res.data.rejectNum;
                        this.achievement.acceptNum = res.data.acceptNum;
                    }
                })
            },
            getUserInfo() {
                getUserByUsername({username: getUsername()}).then((res) => {
                    if (res.code === 0) {
                        this.userInfo.headImg = res.data.headImg;
                        this.userInfo.description = res.data.description;
                        this.userInfo.profession = res.data.profession;
                        this.userInfo.nickname = res.data.nickname;
                    }
                })
            },
            saveUserInfo(formName) {
                this.userInfo.username = getUsername();
                // 为表单绑定验证功能
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        updateByUsername(this.userInfo).then((res) => {
                            if (res.code === 0) {
                                this.editUserDialogVisible = false;
                                ElMessage.success('保存成功')
                            }
                        })
                    } else {
                        return false;
                    }
                });
            },
            handleAvatarSuccess(response, uploadFile) {
                this.userInfo.headImg = response.data[0];
                console.log(this.userInfo)
            },
            beforeAvatarUpload(rawFile) {
                this.headerParams._username = getUsername();
                this.headerParams.AUTHORIZATION = getToken();
                if ('image/jpeg,image/png,image/gif'.indexOf(rawFile.type) === -1) {
                    ElMessage.error('Avatar picture must be JPG/PNG/GIF format!')
                    return false
                } else if (rawFile.size / 1024 / 1024 > 2) {
                    ElMessage.error('Avatar picture size can not exceed 2MB!')
                    return false
                }
                return true
            },
            async onUploadImg(files, callback) {
                const res = await Promise.all(
                    Array.from(files).map((file) => {
                        return new Promise((rev, rej) => {
                            const form = new FormData();
                            form.append('multipartFile', file);
                            uploadImp(form).then((res) => {
                                if (res.code === 0) {
                                    console.log(res.data);
                                    callback(res.data);
                                }
                            }).catch((error) => rej(error));
                        });
                    })
                );

                callback(
                    res.map((item) => item.data)
                );
            },
            commitAnswer() {
                saveAnswer({
                    bugId: this.detailId,
                    content: this.answerText,
                    username: getUsername(),
                    beAnsweredUsername: this.beAnsweredUsername
                }).then((res) => {
                    if (res.code === 0) {
                        let data = res.data;
                        this.answerQuestionDialogVisible = false;
                        let detailAnswered = {};
                        detailAnswered.id = data.id;
                        detailAnswered.username = getUsername();
                        detailAnswered.content = this.answerText;
                        detailAnswered.userAction = '「' + res.data.nickname + '」于 ' + res.data.createTimeStr + ' 回复' + '「' + res.data.beAnsweredNickname + '」';
                        detailAnswered.acceptNum = 0;
                        detailAnswered.rejectNum = 0;
                        detailAnswered.nickname = res.data.nickname;
                        detailAnswered.beAnsweredNickname = res.data.beAnsweredNickname
                        this.detailList.push(detailAnswered);


                        ElNotification({
                            title: 'Success',
                            message: '回复成功',
                            type: 'success'
                        })
                    }
                })
            },
            // 回复
            answerQuestion(data) {
                this.answerText = '';
                if (!getUsername() || !getToken()) {
                    this.registerDialogVisible = false;
                } else {
                    this.beAnsweredUsername = data.username;
                    this.beAnsweredNickname = data.nickname;
                    // 有登录信息，展示信息输入框
                    this.answerQuestionDialogVisible = true;

                }
            },
            bugDetail(bug) {
                this.detailList = [];
                this.answerQuestionDialogVisible = false;
                this.beAnsweredUsername = '';
                list({bugId: bug.id, murmur: getMurmur(), username: getUsername()}).then((res) => {
                    if (res.code === 0) {
                        let detail = {};
                        this.detailId = bug.id;
                        this.detailTitle = bug.title;
                        detail.username = bug.username;
                        detail.title = bug.title;
                        detail.content = bug.content;
                        detail.userAction = '「' + bug.nickname + '」于 ' + bug.createTimeStr + '提出该问题';
                        detail.nickname = bug.nickname;
                        this.detailList.push(detail);

                        let data = res.data;
                        if (data.length > 0) {
                            for (let i = 0; i < data.length; i++) {
                                let detailAnswered = {};
                                detailAnswered.id = data[i].id;
                                detailAnswered.username = data[i].username;
                                detailAnswered.content = data[i].content;
                                detailAnswered.userAction = '「' + data[i].nickname + '」于 ' + data[i].createTimeStr + ' 回复' + '「' + data[i].beAnsweredNickname + '」';
                                detailAnswered.acceptNum = data[i].acceptNum;
                                detailAnswered.rejectNum = data[i].rejectNum;
                                detailAnswered.currentHasAccept = data[i].currentHasAccept;
                                detailAnswered.currentHasReject = data[i].currentHasReject;
                                detailAnswered.nickname =  data[i].nickname;
                                detailAnswered.beAnsweredNickname = data[i].beAnsweredNickname;
                                this.detailList.push(detailAnswered);
                            }
                        }
                        this.detailDialogVisible = true;
                    }
                })
            },
            loadBugPageList() {
                this.pageListCondition.page += 1;
                userCenterPageList(this.pageListCondition).then((res) => {
                    if (res.code === 0) {
                        if (res.data.records.length !== 0) {
                            this.bugList = this.bugList.concat(res.data.records);
                            this.total = res.data.total;
                        } else {
                            this.disabledScroll = true
                            this.pageListCondition.page -= 1;
                        }
                    }
                });
            },
            selectCondition(str) {
                this.pageListCondition.searchCondition = str;
                this.bugPageList();
            },
            bugPageList() {
                this.pageListCondition.page = 1;
                this.disabledScroll = false;
                userCenterPageList(this.pageListCondition).then((res) => {
                    if (res.code === 0) {
                        this.bugList = res.data.records;
                        this.total = res.data.total;

                        if (res.data.records.length < this.pageListCondition.limit) {
                            this.disabledScroll = true
                        }
                    }
                });
            },
        }
    }
</script>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 50%;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        text-align: center;
    }
</style>

